import Config from './config.js'
import Util from './util.js'
import siteConfig from './siteConfig.js';

const app_type = '1';
const app_type_name = 'PDA小程序版';

export default {
	sendRequest(params) {
		if (!Config.basePdaUrl) {
			uni.showToast({
				title: '未配置请求域名',
				'icon': 'none',
				duration: 10000
			});
			return;
		}
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		var method = params.data != undefined ? 'POST' : 'GET', // 请求方式
			url = Config.basePdaUrl + params.url, // 请求路径
			data = {
				app_type,
				app_type_name
			};

		var token = uni.getStorageSync('pdatoken') || '';
		var header = params.header;
		if (!header) {
			header = {}
		}
		header['lr-pda-token'] = token
		header['content-type'] = 'application/json'
		if (params.data != undefined) Object.assign(data, params.data);
		//同步
		return new Promise((resolve, reject) => {
			uni.request({
				url: url,
				method: method,
				data: data,
				header: header,
				dataType: params.dataType || 'json',
				responseType: params.responseType || 'text',
				success: (res) => {
					uni.hideLoading();
					if (res.data.code == 401) {
						uni.removeStorageSync('pdatoken');
						uni.reLaunch({
							url: "/PDA/pages/login"
						})
						return false
					}
					resolve(res.data);
				},
				fail: (res) => {
					uni.hideLoading();
					if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
						uni.showToast({
							title: url + '不在request 合法域名列表中',
							'icon': 'none',
							duration: 10000
						});
						return;
					}
					reject(res);
				},
				complete: (res) => {
					if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200,
							500
						].indexOf(res.statusCode) == -1)) {
						uni.showToast({
							title: url + '请求失败',
							'icon': 'none',
							duration: 10000
						});
						return;
					}
					reject(res.data);
				}
			});
		});

	},
	upload(params) {
		uni.showLoading({
			title: '上传中...',
			mask: true
		});
		uni.uploadFile({
			url: Config.baseUrl + params.url + '?driver=' + siteConfig.upload.mode,
			filePath: params.filePath,
			name: params.name || 'file',
			fileType: params.fileType || 'image',
			formData: {
				app_type,
				app_type_name,
			},
			header: {
				'Batoken': uni.getStorageSync('batoken')
			},
			success: (res) => {
				uni.hideLoading();
				typeof params.success == 'function' && params.success(JSON.parse(res.data));
			},
			fail: (res) => {
				uni.hideLoading();
				typeof params.fail == 'function' && params.fail(res);
			}
		});
	}
}